<html>
<head>
<script>

var ws = null;
var msg_id = 0;

function connect() {
    if (ws !== null) return log('already connected');
    ws = new WebSocket('ws://127.0.0.1:8088/WebSocket');
    ws.onopen = function () {
        log('connected');
    };
    ws.onerror = function (error) {
        log(error);
    };
    ws.onmessage = function (e) {
        log('recv: ' + e.data);
    };
    ws.onclose = function () {
        log('disconnected');
        ws = null;
    };
    return false;
}

function disconnect() {
    if (ws === null) return log('already disconnected');
    ws.close();
    return false;
}

function Send() {
    if (ws === null) return log('please connect first');
    var p1 = document.getElementById('p1').value;
    document.getElementById('p1').value = "";

    var data = {
        "msg_id": msg_id, 
        "action": "examples.test.broadCast", 
        "payload": p1,
        "nickname": "hqy",
        "to": ["hqy2"]
    }

    var jsonData = JSON.stringify(data)
    ws.send(jsonData);
    msg_id = msg_id + 1
    log('send : ' + jsonData);

    return false;
}

function SendSession() {
    var data = {
        "app_name": "myapp",
        "tag" : "hqy",
        "session_id": "d380b6bea4c901c252581ef4633a7906"
    }

    var jsonData = JSON.stringify(data);
    ws.send(jsonData);
    log('send : ' + jsonData);

    return false;
}

function log(text) {
    var li = document.createElement('li');
    li.appendChild(document.createTextNode(text));
    document.getElementById('log').appendChild(li);
    return false;
}

</script>

</head>
<body>
<form onsubmit="return Send();">
    <button type="button" onclick="return connect();">
        Connect
    </button>
    <button type="button" onclick="return disconnect();">
        Disconnect
    </button>
    content: <input id="p1" type="text">

    <button type="submit">Send</button>
</form >

<form onsubmit="return SendSession();">
      <button type="submit">SendSession</button>
</form>

<ol id="log"></ol>
</body>
</html>
